import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { CreateCartDto } from '../dto/cart/create-cart';
import { UpdateCartDto } from '../dto/cart/update-cart';
import { InjectRepository } from '@nestjs/typeorm';
import { CartEntity } from '../entities/cart.entity';
import { Repository } from 'typeorm';
import { Goods } from 'src/module/grocery/entities/goods.entity';

@Injectable()
export class CartService {
  constructor(
    @InjectRepository(CartEntity) private cartRepository: Repository<CartEntity>,
    @InjectRepository(Goods) private goodsRepository: Repository<Goods>
  ) {}

  async create(createCartDto: CreateCartDto, userId: number) {
    try {
      const goods = await this.goodsRepository.findOneBy({id: createCartDto.productId})
      const row = new CartEntity({
        product: goods,
        userId,
        specsId: createCartDto.specsId,
        sum: createCartDto.sum
      })
      const result = this.cartRepository.save(row)
      if (result) {
        return '成功加入购物车'
      }
      return '加入购物车失败'
    } catch(e) {
      throw new ServiceUnavailableException(e)
    }
  }

  async update(userId: number, id: number, updateCartDto: UpdateCartDto) {
    // return `This action updates a #${id} grocery`;
    try {
      const data = this.cartRepository.findOneBy({id})
      const row = new CartEntity({
        ...data,
        sum: updateCartDto.sum
      })
      const result = this.cartRepository.save(row);
      if (result) {
        return '更新成功';
      }
      return '更新失败';
    } catch(e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async findAll(userId: number, pageDto: { pageNo: number; pageSize: number }) {
    try {
      const result = await this.cartRepository.find({
        where: { userId },
        relations: ['product'],
        skip: (pageDto.pageNo - 1) * pageDto.pageSize,
        take: pageDto.pageSize,
      })

      return result || []
    } catch(e) {
      throw new ServiceUnavailableException(e)
    }
  }

  async findOne(id: number) {
    // return `This action returns a #${id} grocery`;
    try {
      const res = await this.cartRepository.findOneBy({ id })
      return res
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const { affected } = await this.cartRepository.delete({ id });
      if (affected) {
        return '成功删除购车产品';
      }
      return '删除购车产品失败';
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
